//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by 潇 on 15/12/15.
//  Copyright © 2015年 潇. All rights reserved.
//

//token 相当于用户请求令牌


import UIKit
import AFNetworking

//封装网络请求 和 业务逻辑
class UserAccountViewModel: NSObject {

    
    //定义用户登录模型对象属性
    var userAccount: UserAccount?
    
    override init() {
        //构造对象先构造本类,再构造父类
//        self.name = name
        userAccount = UserAccount.loadAccount()
        super.init()
    }
    
    //计算型属性,用户是否登录
    var userLogin: Bool {
        return userAccount?.access_token != nil
    }
    
    //用户头像 url
    var headURL: NSURL? {
        let url = NSURL(string: userAccount?.avatar_large ?? "")
        return url
    }
    
    //用户名
    var userName: String? {
     return userAccount?.name
    }
    
    //
    var token :String? {
        return userAccount?.access_token
    }
    
    //加载用户 token(请求标识)
    func loadAccessToken(code: String, finished: (isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        
        NetworkTools.sharedTools.requestJSONDict(.POST, urlString:urlString, parameters: parameters) { (dict, error) -> () in
//            print(dict)
            if error != nil {
                //说明请求失败
                //执行失败的回调
                finished(isSuccess: false)
                return
            }
            //字典转模型
            let userAccount = UserAccount(dict: dict!)
            
            self.loadUserInfo(userAccount, finished: finished)
        }
        
//        let AFN = AFHTTPSessionManager()
//        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        AFN.POST(urlString, parameters: parameters, progress: { (Progress) -> Void in
////            print(Progress)
//            }, success: { (_, result) -> Void in
////                print(result)
//                //获取 token 成功
//                //获取用户信息
//                //判断是否为空,如果不为空,就转行格式
//                if let dict = result as? [String : AnyObject] {
//                    
//                    //                    let token = dict["access_token"] as! String
//                    //                    let uid = dict["uid"] as! String
//                    //                    self.loadUserInfo(token, uid: uid)
//                    
//                    //字典转模型
//                    let userAccount = UserAccount(dict: dict)
//                    //                    print(userAccount) //内存地址
//                    
//                    self.loadUserInfo(userAccount, finished: finished)
//                    
//                }
//                
//            }) { (_, error) -> Void in
////                print(error)
//                finished(isSuccess: false)
//        }
        
    }
    //获取用户信息
    private func loadUserInfo(account: UserAccount, finished: (isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        //字典转不能存放空对对象 nil  [NSNull null]
        if let token = account.access_token,userId = account.uid {
            
            let parameters = ["access_token":token, "uid":userId]
            
            NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters, finished: { (dict, error) -> () in
                if error != nil {
                    //执行失败的回调
                    finished(isSuccess: false)
                    return
                }
                //用户个人地址
                let avatar_large = dict!["avatar_large"] as! String
                //用户昵称
                let name = dict!["name"] as! String
                //给 account 对象的属性做赋值操作
                account.name = name;
                account.avatar_large = avatar_large
                //获取用户信息的完整自定义对象
                //存储自定义对象
                account.saveAccount()
                //                        print(account)
                //执行成功的回调
                finished(isSuccess: true)
            })
            
//            let AFN = AFHTTPSessionManager()
//            //        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
//            AFN.GET(urlString, parameters: parameters, progress: { (_) -> Void in
//                
//                }, success: { (_, result) -> Void in
////                    print(result)
//                    if let dict = result {
//                        //用户个人地址
//                        let avatar_large = dict["avatar_large"] as! String
//                        //用户昵称
//                        let name = dict["name"] as! String
//                        //给 account 对象的属性做赋值操作
//                        account.name = name;
//                        account.avatar_large = avatar_large
//                        //获取用户信息的完整自定义对象
//                        //存储自定义对象
//                        account.saveAccount()
////                        print(account)
//                        //执行成功的回调
//                        finished(isSuccess: true)
//                    }
//                }) { (_, error) -> Void in
////                    print(error)
//                    finished(isSuccess: false)
//                    
//            }
        }
    }

}
